<script setup lang="ts">
import LabPlatformCard from "./components/LabPlatformCard.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { computed, onMounted, ref } from "vue";
import DialogForm from "./components/DialogForm.vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import AddFill from "@iconify-icons/ri/add-circle-line";
import {
  deletePlatform,
  LabPlatformVO,
  listPlatforms,
  listPagePlatforms,
  listParentPlatform
} from "@/api/LabPlatformApi";
import { removeExpDevice } from "@/api/LabExperimentApi";
import { useUserStoreHook } from "@/store/modules/user";
import { getRunningExperiments } from "@/api/LabExperimentApi";

defineOptions({
  name: "LabPlatformList"
});

const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `;

const username = computed(() => {
  return useUserStoreHook()?.username;
});

const INITIAL_DATA: LabPlatformVO = {
  name: "",
  desc: "",
  curUser: username,
  copyFrom: ""
};

const pagination = ref({ current: 1, pageSize: 10, total: 0 });
const labPlatformData = ref([]);
const dataLoading = ref(true);

const getLabPlatformData = async () => {
  try {
    const pageResult = await listParentPlatform({
      curPage: pagination.value.current,
      pageSize: pagination.value.pageSize,
      showParent: true
    });
    console.log("pageResult", pageResult);
    labPlatformData.value = pageResult.data;
    console.log("labPlatformData", labPlatformData);
    labPlatformData.value.forEach(item => {
      // console.log(item);
      // item.sensors.forEach(sensor => {
      //   if (sensor.name === "[NotFound]") {
      //   }
      //   console.log(sensor);
      // });
      item.sensors = item.sensors.filter(sensor => {
        sensor.disabled = true;
        if (sensor.name === "[NotFound]") {
          removeExpDevice({ expId: item.id, deviceId: sensor.deviceId });
          return false; // 删除sensor
        }
        return true; // 保留sensor
      });
    });
    labPlatformData.value.sort((a, b) => {
      const timeA = new Date(a.createTime);
      const timeB = new Date(b.createTime);

      return timeB - timeA;
    });
    console.log("labPlatformData", labPlatformData.value);
    pagination.value = {
      current: pageResult.curPage,
      pageSize: pageResult.pageSize,
      total: pageResult.total
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};
const disabled = ref(false);
onMounted(async () => {
  getLabPlatformData();
  const res = await getRunningExperiments();
  if (!res.errorCode) {
    if (res.data) {
      disabled.value = true;
    }
    console.log(res);
  } else {
    message(`${res.message}`, { type: "error" });
  }
});

const formDialogVisible = ref(false);
const formData = ref({ ...INITIAL_DATA });
const searchValue = ref("");

const onPageSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.current = 1;
  getLabPlatformData();
};
const onCurrentChange = (current: number) => {
  pagination.value.current = current;
  getLabPlatformData();
};
const handleDeleteItem = product => {
  ElMessageBox.confirm(
    product
      ? `确认删除后${product.name}的所有实验信息将被清空, 且无法恢复`
      : "",
    "提示",
    {
      type: "warning"
    }
  )
    .then(async () => {
      const ret = await deletePlatform(product.id);
      if (ret.errorCode === 0) {
        message("删除成功", { type: "success" });
        getLabPlatformData();
      } else {
        console.log(ret);
        message(
          `该实验平台下存在其他配置或历史实验，请删除相关数据后再次删除平台${ret.message}`,
          { type: "error" }
        );
      }
    })
    .catch(() => {});
};
const handleManageProduct = product => {
  formData.value = { ...product, expId: product.id };
  formDialogVisible.value = true;
};

const handleAddProduct = () => {
  formData.value.expId = null;
  formData.value.id = null;
  formDialogVisible.value = true;
};
</script>

<template>
  <div class="main">
    <div class="w-full flex justify-between mb-4">
      <!--      <el-input-->
      <!--        style="width: 300px"-->
      <!--        v-model="searchValue"-->
      <!--        placeholder="请输入实验平台名称"-->
      <!--        clearable-->
      <!--      >-->
      <!--        <template #suffix>-->
      <!--          <el-icon class="el-input__icon">-->
      <!--            <IconifyIconOffline-->
      <!--              v-show="searchValue.length === 0"-->
      <!--              :icon="Search"-->
      <!--            />-->
      <!--          </el-icon>-->
      <!--        </template>-->
      <!--      </el-input>-->

      <el-button
        :disabled="disabled"
        :icon="useRenderIcon(AddFill)"
        @click="handleAddProduct"
      >
        添加
      </el-button>
    </div>
    <!-- {{ labPlatformData }} -->
    <!-- {{ pagination }}
    {{ dataLoading }} -->
    <div
      v-loading="dataLoading"
      :element-loading-svg="svg"
      element-loading-svg-view-box="-10, -10, 50, 50"
      class="card-list-container"
    >
      <el-empty
        description="暂无数据"
        v-show="
          labPlatformData.filter(item =>
            item.name.toLowerCase().includes(searchValue)
          ).length === 0
        "
      />
      <template v-if="pagination.total > 0">
        <el-row :gutter="0">
          <el-col
            v-for="(labPlatform, index) in labPlatformData.filter(item =>
              item.name.toLowerCase().includes(searchValue)
            )"
            :key="index"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="4"
          >
            <LabPlatformCard
              :isRuning="disabled"
              :labPlatform="labPlatform"
              @delete-item="handleDeleteItem"
              @manage-product="handleManageProduct"
            />
          </el-col>
        </el-row>
        <el-pagination
          class="float-right"
          v-model:currentPage="pagination.current"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 100]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="onPageSizeChange"
          @current-change="onCurrentChange"
          style="margin-top: 12px; margin-bottom: 12px"
        />
      </template>
    </div>

    <DialogForm
      v-model:visible="formDialogVisible"
      :data="formData"
      @add-item="getLabPlatformData"
    />
  </div>
</template>
<style lang="scss" scoped>
.card-list-container {
  border-top: var(--el-card-border-color) solid 1px;
  border-left: var(--el-card-border-color) solid 1px;
}
</style>
